from flask import Flask, jsonify, request, render_template
from flask_cors import CORS
import pymysql
from pymysql.cursors import DictCursor
from functools import wraps

app = Flask(__name__)
CORS(app)

@app.route('/')
def index():
    return render_template('exam.html')

# MySQL配置
DB_CONFIG = {
    'host': '43.138.190.205',
    'user': 'root',
    'password': '1qaz@WSX#EDC',
    'database': 'linux_exam',
    'port': 3306,
    'charset': 'utf8mb4',
    'cursorclass': DictCursor
}

# 数据库连接装饰器
def with_db_connection(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        conn = None
        try:
            conn = pymysql.connect(**DB_CONFIG)
            return f(conn, *args, **kwargs)
        except pymysql.Error as e:
            return jsonify({'error': f"数据库错误: {str(e)}"}), 500
        finally:
            if conn:
                conn.close()
    return decorated_function

# 参数验证装饰器
def validate_book_params(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        number = request.args.get('number')
        name = request.args.get('name')
        author = request.args.get('author')
        
        if not all([number, name, author]):
            return jsonify({'error': '缺少必要的参数'}), 400
            
        return f(*args, **kwargs)
    return decorated_function

# 添加图书
@app.route('/add_book', methods=['GET'])
@with_db_connection
@validate_book_params
def add_book(conn):
    number = request.args.get('number')
    name = request.args.get('name')
    author = request.args.get('author')
    
    try:
        with conn.cursor() as cursor:
            cursor.execute(
                'INSERT INTO t_book (number, name, author) VALUES (%s, %s, %s)',
                (number, name, author)
            )
        conn.commit()
        return jsonify({'message': '添加成功'})
    except pymysql.err.IntegrityError:
        return jsonify({'error': '图书编号已存在'}), 400

# 获取所有图书
@app.route('/list_book', methods=['GET'])
@with_db_connection
def list_book(conn):
    with conn.cursor() as cursor:
        cursor.execute('SELECT number, name, author FROM t_book ORDER BY number')
        books = cursor.fetchall()
        return jsonify(books)

# 获取单本图书
@app.route('/get_book', methods=['GET'])
@with_db_connection
def get_book(conn):
    number = request.args.get('number')
    if not number:
        return jsonify({'error': '缺少图书编号'}), 400
        
    with conn.cursor() as cursor:
        cursor.execute(
            'SELECT number, name, author FROM t_book WHERE number = %s',
            (number,)
        )
        book = cursor.fetchone()
        if not book:
            return jsonify({'error': '图书不存在'}), 404
        return jsonify(book)

# 删除图书
@app.route('/delete_book', methods=['GET'])
@with_db_connection
def delete_book(conn):
    number = request.args.get('number')
    if not number:
        return jsonify({'error': '缺少图书编号'}), 400
        
    with conn.cursor() as cursor:
        cursor.execute('SELECT 1 FROM t_book WHERE number = %s', (number,))
        if not cursor.fetchone():
            return jsonify({'error': '图书不存在'}), 404
            
        cursor.execute('DELETE FROM t_book WHERE number = %s', (number,))
        conn.commit()
        return jsonify({'message': '删除成功'})

# 更新图书
@app.route('/update_book', methods=['GET'])
@with_db_connection
@validate_book_params
def update_book(conn):
    number = request.args.get('number')
    name = request.args.get('name')
    author = request.args.get('author')
    
    with conn.cursor() as cursor:
        cursor.execute('SELECT 1 FROM t_book WHERE number = %s', (number,))
        if not cursor.fetchone():
            return jsonify({'error': '图书不存在'}), 404
            
        cursor.execute(
            'UPDATE t_book SET name = %s, author = %s WHERE number = %s',
            (name, author, number)
        )
        conn.commit()
        return jsonify({'message': '更新成功'})

# 错误处理
@app.errorhandler(404)
def not_found_error(error):
    return jsonify({'error': '未找到请求的资源'}), 404

@app.errorhandler(500)
def internal_error(error):
    return jsonify({'error': '服务器内部错误'}), 500

if __name__ == '__main__':
    app.run(debug=True)
